<template>
  <div class="chat-container">
    <div class="message-container" ref="messageContainer">
      <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message', message.type + '-message']"
      >
        <div v-if="message.type === 'bot'" v-html="renderMarkdown(message.content)"></div>
        <div v-else>{{ message.content }}</div>
      </div>
    </div>
    <div v-if="isBotTyping" class="typing-indicator">
      AI 正在思考...
    </div>
    <div class="input-container">
      <input
          v-model="inputMessage"
          @keyup.enter="sendMessage"
          placeholder="输入您的问题..."
          class="message-input"
          :disabled="!isConnected"
      >
      <button
          @click="sendMessage"
          class="send-button"
          :disabled="!isConnected || isBotTyping"
      >
        发送
      </button>
    </div>
    <div v-if="!isConnected" class="connection-status">
      连接已断开，正在重新连接...
    </div>
  </div>
  <div class="footer">
    <div>社区养老服务整合平台</div>

  </div>
</template>

<script>
import SockJS from 'sockjs-client/dist/sockjs.min';
import {marked} from 'marked';
import DOMPurify from 'dompurify';
import {getLoginerInfo} from '../../service/userApi.js'

marked.setOptions({
  gfm: true,
  breaks: true,
  highlight: function (code, lang) {
    return code;
  }
});

export default {
  name: 'ChatWindow',
  data() {
    return {
      ws: null,
      messages: [],
      inputMessage: '你好！',
      isConnected: false,
      userId: '',
      reconnectAttempts: 0,
      maxReconnectAttempts: 5,
      currentResponse: '',
      isBotTyping: false,
      botTypingTimeout: null
    }
  },
  mounted() {
    this.getUserInfo()
    this.initWebSocket()
  },
  beforeDestroy() {
    this.closeWebSocket()
    if (this.botTypingTimeout) clearTimeout(this.botTypingTimeout)
  },
  methods: {
    async getUserInfo() {
      try {
        const userInfo = await getLoginerInfo();
        this.userId = userInfo.data.id;
      } catch (error) {
        console.error('获取用户信息失败:', error);
        this.appendMessage('error', '登录信息获取失败，请刷新页面重试');
      }
    },
    initWebSocket() {
      try {
        this.ws = new SockJS('/ws/chat?userId=' + this.userId);
        this.ws.onopen = () => {
          console.log('WebSocket连接已建立');
          this.isConnected = true;
          this.reconnectAttempts = 0;
        };

        this.ws.onmessage = (event) => {
          if (event.data) {
            try {
              const response = JSON.parse(event.data);
              if (response.error) {
                this.appendMessage('error', response.error);
              } else {
                this.appendMessage('bot', response.content || event.data);
              }
            } catch (e) {
              this.appendMessage('bot', event.data);
            }
          }
        };

        this.ws.onerror = (error) => {
          console.error('WebSocket错误:', error);
          this.isConnected = false;
          this.appendMessage('error', '连接发生错误，正在尝试重新连接...');
        };

        this.ws.onclose = () => {
          this.isConnected = false;
          this.isBotTyping = false;
          this.reconnect();
        };
      } catch (error) {
        console.error('WebSocket初始化失败:', error);
        this.isConnected = false;
        this.appendMessage('error', '连接初始化失败，请刷新页面重试');
      }
    },

    closeWebSocket() {
      if (this.ws) {
        this.ws.close();
        this.ws = null;
      }
    },

    reconnect() {
      if (this.reconnectAttempts < this.maxReconnectAttempts) {
        this.reconnectAttempts++;
        console.log(`尝试重新连接... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
        setTimeout(() => {
          this.initWebSocket();
        }, 3000);
      }
    },

    sendMessage() {
      if (this.inputMessage.trim() && this.isConnected && !this.isBotTyping) {
        this.isBotTyping = true;
        this.ws.send(this.inputMessage);
        this.appendMessage('user', this.inputMessage);
        this.inputMessage = '';
      }
    },

    renderMarkdown(content) {
      return DOMPurify.sanitize(marked(content));
    },

    appendMessage(type, content) {
      if (type === 'user') {
        this.messages.push({
          type,
          content
        });
        this.currentResponse = '';
        this.messages.push({
          type: 'bot',
          content: ''
        });
      } else if (type === 'bot') {
        this.currentResponse += content;
        if (this.messages.length > 0) {
          this.messages[this.messages.length - 1].content = this.currentResponse;
        }
        if (this.botTypingTimeout) clearTimeout(this.botTypingTimeout);
        this.botTypingTimeout = setTimeout(() => {
          this.isBotTyping = false;
        }, 1800);
      } else {
        this.messages.push({
          type,
          content
        });
      }

      this.$nextTick(() => {
        const container = this.$refs.messageContainer;
        container.scrollTop = container.scrollHeight;
      });
    }
  }
}
</script>

<style scoped>
.chat-container {
  max-width: 800px;
  width: 600px;
  border-radius: 10px;
  margin: 10px auto;
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
  background: #fff;
}

.message-container {
  flex: 1;
  border: 1px solid #ddd;
  border-radius: 14px;
  padding: 20px;
  overflow-y: auto;
  margin-bottom: 20px;
  background: #f9f9f9;
}

.input-container {
  margin-bottom: 5px;
  display: flex;
  gap: 10px;
  padding: 0 20px;
}

.message-input {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s;
}

.message-input:focus {
  border-color: #409EFF;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.3);
}

.message-input:disabled,
.send-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.send-button {
  padding: 0 20px;
  background: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s;
  font-weight: bold;
}

.send-button:hover:not(:disabled) {
  background: #66b1ff;
}

.message {
  margin: 10px 0;
  padding: 10px 15px;
  border-radius: 12px;
  max-width: 80%;
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.5;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.user-message {
  color: #409EFF;
  background: #ecf5ff;
  margin-left: auto;
  border-top-left-radius: 4px;
}

.bot-message {
  color: #67C23A;
  background: #f0f9eb;
  font-size: 14px;
  font-family: "Microsoft YaHei", sans-serif;
  border-top-right-radius: 4px;
}

.connection-status {
  text-align: center;
  color: #ff4d4f;
  margin-top: 10px;
  padding: 6px;
  background: #fff0f0;
  border-radius: 4px;
}

.typing-indicator {
  text-align: center;
  color: #909399;
  margin-top: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}
.footer {
  font-size: 14px;
  border-top: 1px solid #e9e9e9;
  display: flex;
  flex-direction: row; /* 水平排列 */
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.beian-footer {
  bottom: 0;
  text-align: center;

a {
  color: #1D1D26;
  font-size: 14px;
  text-decoration-line: underline;

&:hover {
   color: #409EFF;
 }
}
}

</style>